package org.bigdata.framework.core.websocket;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
/**
* ClassName:Global
* Function: TODO ADD FUNCTION.
* @author hxy
*/
public class Global {
	private static Map<String,Integer>onlineNumber=new HashMap<String, Integer>();
	public static  ConcurrentHashMap<String, ChannelGroup> ChannelGroups = new ConcurrentHashMap<String, ChannelGroup>();
	
	public static synchronized void addChannelGroup(String id, Channel channel){
		if(ChannelGroups.get(id)==null){
			ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
			channelGroup.add(channel);
			ChannelGroups.put(id, channelGroup);
			channelGroup=null;
		}else{
			 ChannelGroup channelGroup = ChannelGroups.get(id);
			 if(channelGroup.find(channel.id())==null){
				channelGroup.add(channel);
				ChannelGroups.put(id, channelGroup);
			 }
			 channelGroup=null;
		}
		addOnlineCount(id);
		
	}
	
	public static synchronized void delChannelGroup(String id,Channel channel){
		if(ChannelGroups.get(id)!=null){
			ChannelGroup channelGroup = ChannelGroups.get(id);
			channelGroup.remove(channel);
			ChannelGroups.put(id, channelGroup);
			channelGroup=null;
		}
		subOnlineCount(id);
	}
	
	
	public static synchronized int getOnlineCount(String id) {
		return onlineNumber.get(id);
	}
	
	public static synchronized  Map<String,Integer> getAllOnlineCount(String id) {
		return onlineNumber;
	}
	
	
	public static ChannelGroup getChannelGroup(){
		return new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
	}
	
	private static synchronized void addOnlineCount(String id) {
		if(onlineNumber.get(id)==null){
			onlineNumber.put(id, 1);
		}else{
			onlineNumber.put(id, onlineNumber.get(id)+1);
		}
	}

	private static synchronized void subOnlineCount(String id) {
		if(onlineNumber.get(id)==null||onlineNumber.get(id)<1){
			onlineNumber.put(id, 0);
		}else{
			onlineNumber.put(id, onlineNumber.get(id)-1);
		}
	}
	public static void main(String[] args) {
	
	}
}